import 'package:mysql1/mysql1.dart';

import '../config/Config.dart';

class Sql {
  static var debug_db = 'testdb';
  static var prod_db = 'testdb';
  static ConnectionSettings _settings = ConnectionSettings(
    host: 'localhost',
    port: 3306,
    user: 'cjl',
    db: 'testdb',
    password: '99420',
  );

  Sql._() {}

  static Future<MySqlConnection> GetConn({ConnectionSettings? st}) async {
    if (st == null) {
      if (env == PROD) {
        _settings.db = prod_db;
      } else {
        _settings.db = debug_db;
      }
      return await MySqlConnection.connect(_settings);
    }
    return await MySqlConnection.connect(st);
  }
}

class Query {
  String table;
  int limit;
  String? where;
  String? column;
  String? order_by;
  bool? ASC;
  bool? DESC;

  String? group;

  Query(
     {
     required  this.table,
    this.column = "*",
    this.where,
    this.group,
    this.limit = -1,
    this.order_by,
    this.ASC = true,
    this.DESC = false,
  }) {}

  @override
  String toString() {
    var query = 'select ' + column! + ' from ' + table;

    if (where != null) {
      query = query + ' where (' + where! + ')';
    }

    if (group != null) {
      query = query + ' group by ' + group!;
    }

    if (order_by != null) {
      var order = 'ASC';
      if (DESC == true) {
        order = 'DESC';
      }
      query = query + ' order by ' + order_by! + ' ' + order;
    }

    if (limit > 0) {
      query = query + ' limit ' + limit.toString();
    }

    query = query + ';';
    return query;
  }
}

String sqlStr(String str) {
  return '"' + str + '"';
}
